﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using Jayrock.Json.Conversion;
using Top.Api;
using Top.Api.Parser;
using Top.Api.Util;

namespace TestApi.Api {
	public class XiaoMaClient {

		private string ServerUrl = "http://localhost:4677/api.ashx";
        private string APPKEY = "AndriodCientAppKey";
        private string AppSecret = "AndriodCientSecret";

        private WebUtils webUtils;
		private DefaultTopLogger topLogger;
        private bool disableParser = false; // 禁用响应结果解释
        private bool disableTrace = false; // 禁用日志调试功能
        private IDictionary<string, string> systemParameters; // 设置所有请求共享的系统级参数

        #region DefaultTopClient Constructors

        public XiaoMaClient(string serverUrl,string appkey,string appsecret)
        {
            this.webUtils = new WebUtils();
            this.topLogger = new DefaultTopLogger();
            this.ServerUrl = serverUrl;
            this.APPKEY = appkey;
            this.AppSecret = appsecret;
        }

        #endregion


		public void SetTopLogger(DefaultTopLogger topLogger)
        {
            this.topLogger = topLogger;
        }

        public void SetTimeout(int timeout)
        {
            this.webUtils.Timeout = timeout;
        }

        public void SetDisableParser(bool disableParser)
        {
            this.disableParser = disableParser;
        }

        public void SetDisableTrace(bool disableTrace)
        {
            this.disableTrace = disableTrace;
        }

        public void SetSystemParameters(IDictionary<string, string> systemParameters)
        {
            this.systemParameters = systemParameters;
        }

		public T DoExecute<T>(string apiName, IDictionary<string, string> parameters) where T : TopResponse
		{
			return DoExecute<T>(apiName, parameters,false,null);
		}

        //添加图片到参数里
        public T DoExecute<T>(string apiName, TopDictionary parameters) where T : TopResponse
        {
            return DoExecute<T>(apiName, parameters, parameters.Files.Count != 0, parameters.Files);
        }

		public T DoExecute<T>(string apiName, IDictionary<string, string> parameters,
			bool isNeedUpload,
			IDictionary<string, FileItem> fileParameters) where T : TopResponse
        {
            // 提前检查业务参数
			//try
			//{
			//    request.Validate();
			//}
			//catch (TopException e)
			//{
			//    return createErrorResponse<T>(e.ErrorCode, e.ErrorMsg);
			//}

            // 添加协议级请求参数
			TopDictionary txtParams = new TopDictionary(parameters);
			txtParams.Add("method", apiName);
			txtParams.Add("appkey", APPKEY);
	        txtParams.Add("deviceid", "用户设备号");
            txtParams.Add("timestamp", ConvertToTimestamp(DateTime.Now));
		    txtParams.Add("signmethod", "md5");
			// 添加签名参数
			txtParams.Add("sign", TopUtils.SignTopRequest(txtParams, AppSecret));
            txtParams.AddAll(this.systemParameters);



            string reqUrl = webUtils.BuildGetUrl(ServerUrl, txtParams);
            try
            {
                string body;
				if (isNeedUpload) // 是否需要上传文件
                {
					IDictionary<string, FileItem> fileParams = TopUtils.CleanupDictionary(fileParameters);
					body = webUtils.DoPost(ServerUrl, txtParams, fileParams);
                }
                else
                {
					body = webUtils.DoPost(ServerUrl, txtParams);
                }

                // 解释响应结果
                T rsp;
                if (disableParser)
                {
                    rsp = Activator.CreateInstance<T>();
                    rsp.Body = body;
                }
                else
                {
                    ITopParser tp = new TopJsonParser();
                    rsp = tp.Parse<T>(body);
                }

                // 追踪错误的请求
                if (!disableTrace && rsp.IsError)
                {
                    StringBuilder sb = new StringBuilder(reqUrl).Append(" response error!\r\n").Append(rsp.Body);
                    topLogger.Warn(sb.ToString());
                }
                return rsp;
            }
            catch (Exception e)
            {
                if (!disableTrace)
                {
                    StringBuilder sb = new StringBuilder(reqUrl).Append(" request error!\r\n").Append(e.StackTrace);
                    topLogger.Error(sb.ToString());


                }
                throw e;
            }
        }

        private T createErrorResponse<T>(string errCode, string errMsg) where T : TopResponse
        {
            T rsp = Activator.CreateInstance<T>();
            rsp.ErrCode = errCode;
            rsp.ErrMsg = errMsg;

            
            IDictionary<string, object> errObj = new Dictionary<string, object>();
            errObj.Add("code", errCode);
            errObj.Add("msg", errMsg);
            IDictionary<string, object> root = new Dictionary<string, object>();
            root.Add("error_response", errObj);

            string body = JsonConvert.ExportToString(root);
            rsp.Body = body;
            
            return rsp;
        }

        //获取Unix时间戳
        public static long ConvertToTimestamp(DateTime value)
        {
            //注意转换时区ToLocalTime
            TimeSpan span = (value - new DateTime(1970, 1, 1, 0, 0, 0, 0).ToLocalTime());
            //return the total seconds (which is a unix timestamp)
            return Convert.ToInt64(span.TotalSeconds);
        }

	}
}